
package horde.patterns;

import horde.interfaces.Requests;
import horde.utils.CallMethodByName;
import java.util.Arrays;

/**
 * Default core to extends by the agent cores
 * @author Andres Picazo Cuesta
 * @author Arturo Mazon Tribiño
 */
public class Core {

    private int result = CallMethodByName.METHOD_NOT_REQUESTED_YET;
    protected Requests requests;
    private String id;

    /**
     * Invokes a method from myself given the following parameters
     * @param taskNameAndParameters First param is the method to execute, the others, if any,
     * are the parameters for the method.
     * @return
     */
    public boolean runTask(Object... taskNameAndParameters) {
        String methodName = taskNameAndParameters[0].toString();
        if (methodName.equals("")) return true;
        if (taskNameAndParameters.length == 1) result = CallMethodByName.call(methodName, null, this);
        else result = CallMethodByName.call(methodName, Arrays.copyOfRange(taskNameAndParameters, 1, taskNameAndParameters.length), this);
        if (result == CallMethodByName.METHOD_CALLED) return true;
        else return false;
    }

    /**
     * Gets the result of the last call, as integer value. To check it's meaning as a string call the method
     * getResultMeaning with the return value of this method.
     * Meaning can be checked against the class CallMethodByName (variables are static)
     * @return Integer value returned by from call to CallMethodByName.call(...)
     */
    public int getLastCallResult () {
        return result;
    }

    /**
     * Gets the meaning of a integer value representing the result of the last call invoked from
     * the class CallMethodByName, as a string value
     * @param r Integer value to be interpreted
     * @return String from CallMethodByName corresponding to the integer value 'r'
     */
    public String getResultMeaning (int r) {
        return CallMethodByName.getExitValueMeaning(r);
    }

    /**
     * Gives the core access to the master's public methods throught the requests objects, used for things
     * like getting the node's shared resources (e.g. a shared visualization object)
     * Note: This could be bypassed, this object can also be obtained through the directory
     * @param requests Master's requests object
     */
    public void setRequests (Requests requests) {
        this.requests = requests;
    }

    /**
     * Get the name of the agent the core is providing methods
     * @return Id of the agent
     */
    public String getID () {
        return id;
    }

    /**
     * Informs the core the name of the agent it provides methods.
     */
    public void setID (String id) {
        this.id = id;
    }
}
